
 
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include "mythread.h"

#define NUM_THREADS	3

int numThrd = 0;

/*This is the thread to print hello and each threads ID */
void *printHello(void *num){
	int *inputNum = (int *) num;
    /* The first user created thread will yield to the other two threads, thus thread 2 will print its id last */
    if(mythread_self() == 2){
		mythread_yield();
    }
   
    /* The following shows the successful operation of mythread_self(), it should print 3, then 4, then 2 */
    printf("Hello, my thread ID is: %d\n", mythread_self());
	/* The following shows the successful operation of parameter passing; this will print 0 with the first thread, 1 with the second, and 2 with the third to run (representing their run order) */
	printf("The number you passed is: %d\n\n", *inputNum);
	numThrd++;
   
    /* The last user created thread will yield to the first threads, thus thread 2 will print its id last */
    if(mythread_self() == 4){
		mythread_yield();
    }
   
    mythread_exit(NULL);
    return 0;
}


int main (int argc, char *argv[])
{
    mythread_t thread[NUM_THREADS];
    mythread_attr_t *attr = NULL;
    int tNum = 0;
    int errorCheck;

    /* Create the three threads for printing hello */
    for(tNum = 0; tNum < NUM_THREADS; tNum++)
    {
		errorCheck = mythread_create(&thread[tNum], attr, printHello, (void *) &numThrd);
		if (errorCheck)
		{
			printf("ERROR; return code from mythread_create() for thread %d is %d\n", tNum, errorCheck);
			exit(-1);
        }
    }

    /* This will print the contents of the queue to show that 5 threads have successfully been created and queued */
    /*Following is the contents of the queue after creation to show that 5 threads have successfully been created and queued.  
	 The thread with thread ID 0 will always be the main thread, and the idle thread always has thread ID 1.  Threads 2, 3, and 4 are user-created
	 threads. */
    printQueue();
   
    /* Test mythread_self, should return 0 for the main thread  because it is currently executing here */
    int threadNumber = mythread_self();
    printf("\nmythread_self should return 0, it returns: %d\n\n", threadNumber);
   
    /* Join the other threads, the first user created thread will yield once, so it should finish last */
    void *status;
    for(tNum = 2; tNum < NUM_THREADS; tNum++)
    {
		errorCheck = mythread_join(thread[tNum], &status);
		if (errorCheck)
		{
			printf("ERROR; return code from mythread_join() for thread %d is %d\n", tNum, errorCheck);
			exit(-1);
        }
    }
   
    printf("Main thread exiting via mythread_exit.\n");
	mythread_exit(NULL);

	return 0;
}
